// C source file with the function definitions to handle strings for each encoding

// get_str_byte_length_safe() function
umax get_str_byte_length_safe(void * str, umax ssize, char_enc enc)
{
  // check params
  void * tmp = NULL;
  char_enc old_enc = CHAR_ARR_ENC_STATE;
  if (str == NULL || ssize == 0 || set_ch_arr_enc_state(enc) == CHAR_ENC_UNKNOWN)
    goto end;
  
  // find the NULL character that ends the string (0 valued)
  byte * str_end = find_chint_in_chenc_arr(str, ssize, enc, 0);  
  // return the string size if str_end exists
  if (str_end == NULL)
    goto end;
    
  // return the result
  end:
  set_ch_arr_enc_state(old_enc);
  free_memory(tmp);
  return tmp != NULL ? str_end - (byte *) str : 0;
}

// get_str_char_length_safe() function
umax get_str_char_length_safe(void * str, umax mx_size, char_enc enc)
{
  // check params
  umax str_size = get_str_byte_length_safe(str, mx_size, enc);
  if (str_size == 0)
    return 0;
  
  // count the characters in the string (reuse get_chenc_arr_char_length())
  return get_chenc_arr_ch_length(str, str_size, enc);
}

// get_str_byte_length() function
// function to return a string byte length. It is
// expected that the string is null terminated.
umax get_str_byte_length(void * str, char_enc enc)
{
  // reuse get_str_byte_length_safe()
  return get_str_byte_length_safe(str, MAX_STR_SIZE, enc);
}

// get_str_char_length() function
// function to return a string char length. It is
// expected that the string is null terminated.
umax get_str_char_length(void * str, char_enc enc)
{
  // reuse get_str_char_length_safe()
  return get_str_char_length_safe(str, MAX_STR_SIZE, enc);
}

// print_string() function
// pretty self-explanatory >:]
void print_str(void * str, char_enc enc)
{
  // check if str is valid
  umax str_size = get_str_byte_length(str, enc);
  if (str_size == 0)
    return;
  
  // reuse print_chenc_arr
  print_chenc_arr(str, str_size, enc);
  return;
}

// cp_str() function
// function to copy a string to some location (be sure to have enough space
// for the resulting string!) will return the pointer to the last element written
// (null character). Special case of the cp_mem_bytes() function.
void * cp_str(void * str, char_enc enc, void * dest)
{  
  // check str and dest
  if (str == NULL || dest == NULL)
    return NULL;
  
  // get str length
  umax str_length = get_str_byte_length(str, enc);
  if (str_length == 0)
    return NULL;
  
  // write str into dest
  cp_mem_bytes(str, str_length, dest);
  return ((char *) dest) + str_length - 1;
}

// compare_strings() function
// function to compare 2 strings (null terminated)
// special case of the comp_bytes() function
bool comp_strs(void * str1, char_enc enc, void * str2)
{
  // comparing the bytes should be enough
  return comp_bytes(str1, str2, get_str_byte_length(str1, enc));
}
